package com.treetao.union.web.controller.mall;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.treetao.union.db.model.MallPCata;
import com.treetao.union.db.model.vo.LayerData;
import com.treetao.union.db.model.vo.RestResponse;
import com.treetao.union.db.service.MallPCataService;
import com.treetao.union.web.constant.Constants;
import com.treetao.union.web.controller.BaseController;
import com.treetao.union.web.pojo.CascaderPojo;

/**
 * <p>
 * 商品分类  前端控制器
 * </p>
 *
 * @author Dev.M
 * @since 2020-04-11
 */
@Controller
@RequestMapping(Constants.AMIND_PREFIX + "/mall-pcata")
public class MallPCataController extends BaseController{

    @Autowired
    private MallPCataService mallPCataService;

    @GetMapping("list")
    public String list(){
        return "/admin/mall-pcata/list";
    }

    @PostMapping("list")
    @ResponseBody
    public LayerData<MallPCata> list(@RequestParam(value = "page",defaultValue = "1")Integer page,
                                      @RequestParam(value = "limit",defaultValue = "15")Integer limit,
                                      ServletRequest request){
        Map map = WebUtils.getParametersStartingWith(request, "");
        LayerData<MallPCata> layerData = new LayerData<>();
        QueryWrapper<MallPCata> wrapper = new QueryWrapper<MallPCata>();
        if(!map.isEmpty()){
        	String delFlag = (String) map.get("delFlag");
            if(StringUtils.isNotBlank(delFlag)) {
                wrapper.eq("del_flag",Boolean.valueOf(delFlag));
            }else{
                map.remove("del_flag");
            }
            String name = (String) map.get("name");
            if(StringUtils.isNotBlank(name)) {
                wrapper.like("name",name);
            }else{
                map.remove("name");
            }

            String level = (String) map.get("level");
            if(StringUtils.isNotBlank(level)) {
                wrapper.eq("level",level);
            }else{
                map.remove("level");
            }
            String parentid = (String) map.get("parentid");
            if(StringUtils.isNotBlank(parentid)) {
                wrapper.eq("refcataid",parentid);
            }else{
                map.remove("parentid");
            }

        }
        wrapper.orderByAsc("orderby");
        IPage<MallPCata> pageData = mallPCataService.page(new Page<>(page,limit),wrapper);
        layerData.setData(pageData.getRecords());
        layerData.setCount(pageData.getTotal());
        return layerData;
    }

    //下拉级联组件数据
    @GetMapping("cascaderdata")
    @ResponseBody
    public List<CascaderPojo> cascaderdata(HttpServletRequest req){
    	List<CascaderPojo> result = new ArrayList<CascaderPojo>();
    	//一级
    	QueryWrapper<MallPCata> q = getQueryWrapperNoDel();
    	q.eq("level", 1).isNull("refcataid");
		List<MallPCata> first = mallPCataService.list(q);
		if(first!=null) {
			first.forEach(item -> {
				CascaderPojo firstPojo = new CascaderPojo();
				firstPojo.setLabel(item.getName());
				firstPojo.setValue(String.valueOf(item.getId()));
				QueryWrapper<MallPCata> q2 = getQueryWrapperNoDel();
				q2.eq("refcataid", item.getId());
				List<MallPCata> seconds = mallPCataService.list(q2);
				if(seconds!=null) {
					List<CascaderPojo> listSec = new ArrayList<CascaderPojo>();
					seconds.forEach(sec -> {
						CascaderPojo cp = new CascaderPojo();
						cp.setLabel(sec.getName());
						cp.setValue(String.valueOf(sec.getId()));
						listSec.add(cp);
					});
					firstPojo.setChildren(listSec);
				}
				result.add(firstPojo);
			});
		}
        return result;
    }

    @GetMapping("add")
    public String add(HttpServletRequest req,Model model){
    	Map<String, String[]> params = req.getParameterMap();
    	for(String key : params.keySet()) {
    		model.addAttribute(key,params.get(key)==null?null:params.get(key)[0]);
    	}
    	
        return "/admin/mall-pcata/add";
    }

    @PostMapping("add")
    @ResponseBody
    public RestResponse add(MallPCata mallPCata){
        if(StringUtils.isBlank(mallPCata.getName())){
            return RestResponse.failure("分类名称不能为空");
        }
        mallPCataService.save(mallPCata);
        return RestResponse.success();
    }
    
    @GetMapping("detail")
    public String detail(Long id,Model model){
       MallPCata mallPCata = mallPCataService.getById(id);
        model.addAttribute("mallPCata",mallPCata);
        return "/admin/mall-pcata/detail";
    }

    @GetMapping("edit")
    public String edit(Long id,Model model){
        MallPCata mallPCata = mallPCataService.getById(id);
        model.addAttribute("mallPCata",mallPCata);
        return "/admin/mall-pcata/edit";
    }

    @PostMapping("edit")
    @ResponseBody
    public RestResponse edit(MallPCata mallPCata){
        if(null == mallPCata.getId() || 0 == mallPCata.getId()){
            return RestResponse.failure("ID不能为空");
        }
        if(StringUtils.isBlank(mallPCata.getName())){
            return RestResponse.failure("分类名称不能为空");
        }
        mallPCataService.updateById(mallPCata);
        return RestResponse.success();
    }
    
    @PostMapping("batchDel")
    @ResponseBody
    public RestResponse batchDel(@RequestParam(value = "ids[]",required = false)List<Long> ids){
        if(null == ids || ids.size()==0){
            return RestResponse.failure("请选择一项");
        }
        return RestResponse.success().setDataOnlyResult( mallPCataService.removeByIds(ids));
    }

    @PostMapping("delete")
    @ResponseBody
    public RestResponse delete(@RequestParam(value = "id",required = false)Long id){
        if(null == id || 0 == id){
            return RestResponse.failure("ID不能为空");
        }
        return RestResponse.success().setDataOnlyResult(mallPCataService.removeById(id));
    }
    
    @PostMapping("change-status")
    @ResponseBody
    public RestResponse change_status(@RequestParam(value = "id",required = true)Long id,@RequestParam(value = "status",required = false)Boolean status){
       MallPCata mallPCata = mallPCataService.getById(id);
        mallPCata.setDelFlag(status);
        mallPCataService.updateById(mallPCata);
        return RestResponse.success();
    }

}